/**
 * tzdesk系统平台
 * moonvip_admin
 * com.tz.service.dayprice
 * IDaypriceService.java
 * 创建人:小胡 
 * 时间：2017年02月03日 09:03:56
 *
 */
package com.tz.service.dayprice.impl;

import com.tz.bean.Dayprice;
import com.tz.bean.TzParams;
import com.tz.dao.dayprice.IDaypriceMapper;
import com.tz.service.dayprice.IDaypriceService;
import com.tz.util.TmStringUtils;
import com.tz.util.WebCrawlers;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 今日金价管理serviceImpl
 * IDaypriceService
 * 创建人:小胡 
 * 时间：2017年02月03日 09:03:56
 * @version 1.0.0
 * 
 */
@Service
public class DaypriceServiceImpl implements IDaypriceService{

	@Autowired
	private IDaypriceMapper daypriceMapper;
	
	@Override
	public List<Dayprice> findDayprices(TzParams params){
		if(TmStringUtils.isEmpty(params.getOrder()))params.setOrder("create_time desc");
		return daypriceMapper.findDayprices(params);
	}
	
	@Override
	public int count(TzParams params) {
		return daypriceMapper.count(params);
	}

	@Override
	public HashMap<String ,Object> getDayprice(Integer id) {
		return daypriceMapper.getDayprice(id);
	}

	@Override
	public int save(Dayprice dayprice) {
		return daypriceMapper.save(dayprice);
	}

	@Override
	public void add() {
		List<HashMap<String , Object>> lastRecords = daypriceMapper.getLastRecord();
		daypriceMapper.updateByDeleteCode();
		JSONArray arr = WebCrawlers.getDayGoldPrice();
		HashMap map = null;
		Double fetchPrice = 0.0;
		String fetchRemark = "";
		Dayprice dayprice = new Dayprice();
		for(int i=0,len=arr.size();i<len;i++){
			JSONObject obj = (JSONObject) arr.get(i);
			fetchPrice = obj.getDouble("price");
			fetchRemark = obj.getString("remark");
			dayprice.setPrice(fetchPrice);
			dayprice.setName(fetchRemark);
			if(lastRecords.size()>0){
				for(int j=0,leng=lastRecords.size();j<leng;j++){
					map = lastRecords.get(j);
					String name = (String) map.get("name");
					if(name.equals(fetchRemark)){
						Double d = (Double) map.get("price");
						Double c = fetchPrice;
						if((d-c)/d >=0.05 || (c-d)/d>=0.05 ){
							dayprice.setIsError("002");//异常
						}else{
							dayprice.setIsError("001");
						}
					}
				}
			}else{
				dayprice.setIsError("001");
			}

			dayprice.setCreateTime(new Date());
			daypriceMapper.save(dayprice);
		}
	}

	@Override
	public int update(Dayprice dayprice) {
		return daypriceMapper.update(dayprice);
	}

	@Override
	public int delete(Integer id) {
		return daypriceMapper.delete(id);
	}

    public static void main(String[] args) {
        String s = "123";
        System.out.println(Double.parseDouble(s));
    }
}
